# -*- coding: utf-8 -*-
"""
Author: chen xi
Date: 2025/5/16 下午3:04
File: download_device_config.py
"""

import requests
from requests.auth import HTTPBasicAuth
import os


def download_device_config(save_path=None, host='192.168.101.101', username='admin', password=''):
	"""
	下载设备配置文件

	参数:
		save_path (str): 文件保存路径（可选，默认当前目录下device_config.bin）
		host (str): 设备IP地址（默认192.168.101.101）
		username (str): Basic认证用户名（默认admin）
		password (str): Basic认证密码（默认空）

	返回:
		dict: {
			'status': bool,     # 是否成功
			'file_path': str,   # 保存的文件路径
			'error': str        # 错误信息（如有）
		}
	"""
	# 默认保存路径处理
	if not save_path:
		save_path = os.path.join(os.getcwd(), 'device_config.ini')
	
	# 请求配置
	url = f"http://{host}/System/DeviceConfigFile?FileType=3"
	headers = {
		"Accept": "*/*",
		"Accept-Language": "zh-CN",
		"Connection": "Keep-Alive",
		"Content-Type": "text/xml;charset=utf-8",
		"User-Agent": "SDK C++ http client"
	}
	
	try:
		# 发送请求
		response = requests.get(
			url,
			headers=headers,
			auth=HTTPBasicAuth(username, password),
			timeout=10  # 添加超时设置
		)
		
		# 检查响应状态
		if response.status_code != 200:
			return {
				'status': False,
				'file_path': '',
				'error': f"HTTP {response.status_code} - {response.reason}"
			}
		
		# 保存文件
		with open(save_path, 'wb') as f:
			f.write(response.content)
		
		return {
			'status': True,
			'file_path': os.path.abspath(save_path),
			'error': ''
		}
	
	except Exception as e:
		return {
			'status': False,
			'file_path': '',
			'error': str(e)
		}


# 使用示例
if __name__ == "__main__":
	# 示例2：自定义保存路径
	result = download_device_config(
		save_path="./device_config.ini",
		host="192.168.101.107",
		username="admin",
		password=""
	)
	if result['status']:
		print(f"文件已保存到: {result['file_path']}")
	else:
		print(f"下载失败: {result['error']}")